package cn.itcast.crm.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.crm.dao.CustomerRepository;
import cn.itcast.crm.domain.Customer;
import cn.itcast.crm.service.CustomerService;
@Service
@Transactional
public class CustomerServiceImpl implements CustomerService {
	@Autowired
	private  CustomerRepository dao;
	@Override
	public List<Customer> findNoAssociationCustomers() {
		
		return dao.findByFixedAreaIdIsNull();
	}

	@Override
	public List<Customer> findHasAssociationFixedAreaCustomers(String fixedareaid) {
		return dao.findByFixedAreaId(fixedareaid);
	}

	@Override
	public void associationCustomersToFixedArea(String customerIdStr, String fixedareaid) {
		dao.clearFixedAreaId(fixedareaid);
		
		if(StringUtils.isBlank(customerIdStr)){
			return;
		}
		
		String []customerIdArray = customerIdStr.split(",");
		for (String idStr : customerIdArray) {
			Integer id = Integer.parseInt(idStr);
			dao.updateFixedAreaId(fixedareaid,id);
		}
	}

	@Override
	public void regist(Customer customer) {
		dao.save(customer);
	}

	@Override
	public Customer findByTelephone(String telephone) {
		
		return dao.findByTelephone(telephone);
	}

	@Override
	public void updateType(String telephone) {
		dao.updateType(telephone);
		
	}

	@Override
	public Customer login(String telephone, String password) {
		
		return dao.findByTelephoneAndPassword(telephone,password);
	}

	@Override
	public String findFixedAreaIdByAddress(String address) {
		return dao.findFixedAreaIdByAddress(address);
	}

}
